<?php

defined('SYSPATH') or die('Access error!');

class Model_Shop_Goods extends Model
{

    public $rules = array(
        'name' => array
            (
            'not_empty' => null,
        ),
        'content' => array(
            'not_empty' => null,
        )
    );

    /**
     * 获取产品分类(下拉列表的形式)
     * @param type $id
     * @return type
     */
    public function goods_category_option($id = SHOP_CATEGORY_ID)
    {
        $category = Model_Category::factory('category');
        $category_option = $category->get_category_option2($id);
        return $category_option;
    }

    /**
     *  获得商品的详细信息
     * @param type $goods_id
     * @return type
     */
    public function get_goods_detail($goods_id)
    {
        $sql = 'SELECT g.*,u.id as user_id,u.username,a.file_realname,a.file_path,s.id as store_id ,s.store_logo,s.name as store_name,c.name as category_name ' .
                'FROM ' . $this->table . ' AS g ' .
                'LEFT JOIN ' . $this->db->get_table('shop_goods_attachment') . ' AS ga ON ga.goods_id=g.id ' .
                'LEFT JOIN ' . $this->db->get_table('attachment') . ' AS a ON a.id=ga.attachment_id ' .
                'LEFT JOIN ' . $this->db->get_table('user') . ' AS u ON u.id = g.user_id ' .
                'LEFT JOIN ' . $this->db->get_table('shop_store') . ' AS s ON s.user_id = u.id ' .
                'LEFT JOIN ' . $this->db->get_table('category') . ' AS c ON c.id = g.category_id ' .
                "WHERE g.id = $goods_id AND g.is_delete = 0 " .
                "GROUP BY g.id";

        $goods_detail = $this->db->get_row($sql, ARRAY_A);
        $goods_detail['goods_image'] = $this->create_goods_image($goods_detail['file_path'] . $goods_detail['file_realname'], $goods_detail['user_id']);
        $goods_detail['store_logo'] = Model::factory('shop_store')->create_store_logo($goods_detail['store_logo'], $goods_detail['user_id']);
        $goods_detail['account_str'] = $this->get_goods_account($goods_detail['account'], $goods_detail['account_type']);
        $goods_detail['goods_url'] = $this->create_goods_url($goods_detail['id']);
        $goods_detail['buy_button'] = $this->create_goods_buy_button($goods_detail['account_type'], $goods_detail['id']);
        $goods_detail['store_url'] = URL::site(Route::get('store')->uri(array('action' => 'index', 'id' => $goods_detail['store_id'])));
        return $goods_detail;
    }

    /**
     *  根据购买的类型 生成购买按钮
     * @param type $account_type
     * @return string
     */
    public function create_goods_buy_button($account_type, $goods_id)
    {
        $_token = CSRF::set_csrf_token();
        $button_str = '';
        switch ($account_type)
        {
            case 'free':
                $button_str = "<form action='/order/submit'> <input type='hidden' value='{$_token}' name='_token'><input type='hidden' value='" . $goods_id . "' name='goods_id'><input type='submit' value='免费获取'></form>";
                break;
            case 'points':
                $button_str = "<form action='/order/submit' method='post'> <input type='hidden' value='{$_token}' name='_token'><input type='hidden' value='" . $goods_id . "' name='goods_id'><input type='submit' value='积分兑换'></form>";
                break;
            case 'rmb':
                $button_str = "<a href='/order/submit/" . $goods_id . "'>立即购买</a>";
                break;
            default:
                break;
        }
        return $button_str;
    }

    /**
     *  根据价格的类型,格式化价格输出
     * @param type $account
     * @param type $account_type
     * @return string
     */
    public function get_goods_account($account, $account_type)
    {
        $account_str = '';
        switch ($account_type)
        {
            case 'free':
                $account_str = '免费';
                break;
            case 'points':
                $account_str = '积分：' . $account;
                break;
            case 'rmb':
                $account_str = 'RMB：' . $account;
                break;
            default:
                break;
        }

        return $account_str;
    }

    /**
     *  根据图片的名称和user_id获取图片的地址
     * @param type $goods_image
     */
    public function create_goods_image($goods_image, $user_id)
    {
        return SHOP_GOODS_IMAGES_FILE_PATH . '/' . $user_id . '/' . $goods_image;
    }

    /**
     *  根据产品的id生成产品的链接
     * @param type $goods_id
     * @return type
     */
    public function create_goods_url($goods_id)
    {
        return URL::site(Route::get('goods')->uri(array('id' => $goods_id)));
    }

    /**
     *  通用的查询产品列表(包含分页。如果不需要分页在获取的数据中只要保留下标为list的数据)
     * @param type $where_sql
     * @param type $nums
     * @return type
     */
    public function get_base_list($where_sql = '', $nums = 10)
    {
        if (Arr::validate_arr($where_sql))
        {
            $where_sql = $this->get_table_where('g', $where_sql);
        }
        $sql = 'SELECT g.name,g.user_id,g.id,g.account,g.is_lock,g.add_time,g.account_type,a.file_realname,a.file_path ' .
                'FROM ' . $this->table . ' AS g ' .
                'LEFT JOIN ' . $this->db->get_table('shop_goods_attachment') . ' AS ga ON ga.goods_id = g.id ' .
                "LEFT JOIN " . $this->db->get_table('attachment') . " AS a ON a.id = ga.attachment_id " . $where_sql;
        $data = $this->get_page_list($sql, $nums);
        $goods_temp = $data['list'];
        $goods = array();
        if (Arr::validate_arr($goods_temp))
        {
            foreach ($goods_temp as $value)
            {
                $value['goods_image'] = $this->create_goods_image($value['file_path'] . $value['file_realname'], $value['user_id']);
                $value['account_str'] = $this->get_goods_account($value['account'], $value['account_type']);
                $value['goods_url'] = $this->create_goods_url($value['id']);
                $goods[] = $value;
            }
        }
        $data['list'] = $goods;
        return $data;
    }

    public function get_goods_list($where_sql = '', $nums = 10)
    {
        $where_sql = $this->get_list_where();
        return $this->get_base_list($where_sql, $nums);
    }

    /**
     *  根据所给的条件生成通用where条件
     * @param string $category_id
     * @param string $ext_where
     * @return type
     */
    public function get_list_where($category_id = '', $ext_where = '')
    {
        if (is_array($category_id))
        {
            $children_in = $this->get_in($category_id);
            $category_id = ' AND g.category_id ' . $children_in . " ";
        }
        elseif ($category_id != '')
        {
            $category_id = ' AND g.category_id=' . $category_id . " ";
        }

        if (!empty($ext_where))
        {
            $ext_where = ' AND ' . $ext_where;
        }

        return "WHERE g.is_onsale = 1 AND g.is_delete = 0 AND a.is_image=1 AND g.is_lock=0" . $category_id . $ext_where;
    }

    public function get_list_by_category_id($category_id, $limit_num = 10, $rec = TRUE)
    {
        if ($rec == TRUE)
        {
            $all_children_category = Model::factory('category')->get_all_children($category_id);
        }
        else
        {
            $all_children_category = $category_id;
        }

        $where_sql = $this->get_list_where($all_children_category, $limit_num);
        return $this->get_base_list($where_sql, $limit_num);
    }

    /**
     * 获得指定分类下的推荐商品
     * @param type $store_id
     * @param type $category_id
     * @param type $ext_where
     * @param type $limit_num
     * @return type
     */
    public function get_store_goods($store_id, $category_id = '', $ext_where = '', $limit_num = 10)
    {
        $where_sql = $this->get_list_where($category_id, $ext_where) . " AND store_id=" . $store_id . " ORDER BY g.position,g.id DESC";
        return $this->get_base_list($where_sql, $limit_num);
    }

    /**
     *  获得指定分类下的推荐商品
     * @param type $recommend_type
     * @param type $category_id
     * @param type $ext_where
     * @param type $limit_num
     * @return type
     */
    public function get_category_recommend_goods($recommend_type = '', $category_id = '', $ext_where = '', $limit_num = 10)
    {
        $where_sql = $this->get_list_where($category_id, $ext_where) . " AND g.recommend_type='" . $recommend_type . "' ORDER BY g.position,g.id DESC";
        $goods_list = $this->get_base_list($where_sql, $limit_num);
        return Arr::validate_arr($goods_list['list']) ? $goods_list['list'] : array();
    }

    /**
     *  插入附件
     * @param type $data
     * @return type
     */
    public function add_attachment($data)
    {
        return Model_Attachment::factory('attachment')->insert($data);
    }

    /**
     *  插入商品和附件的关联关系
     * @param type $goods_id
     * @param type $attachment_id
     */
    public function add_goods_attachment($goods_id, $attachment_id)
    {
        $sql = "INSERT " . $this->db->get_table('shop_goods_attachment') . " SET goods_id=" . $goods_id . ",attachment_id=" . $attachment_id;
        $this->db->query($sql);
    }

    public function delete_attachment($goods_id)
    {
        $sql = "SELECT attachment_id FROM " . $this->db->get_table('shop_goods_attachment') . " WHERE goods_id=" . $goods_id;
        $attachment_id = $this->db->get_var($sql);
        $this->db->query('DELETE FROM ' . $this->db->get_table('shop_goods_attachment') . " WHERE goods_id=" . $goods_id);
        if (!empty($attachment_id))
        {
            $attachment_arr = Model::factory('attachment')->get_row(array('id' => $attachment_id), 'file_realname,file_path');
            if (Arr::validate_arr($attachment_arr))
            {
                $goods_attachment_path = SHOP_GOODS_IMAGES_SAVE_PATH . Session::instance()->get_detail('user', 'id') . '/' . $attachment_arr['file_path'] . $attachment_arr['file_realname'];
                $this->db->query('DELETE FROM ' . $this->db->get_table('attachment') . " WHERE id=" . $attachment_id);
                if (file_exists($goods_attachment_path))
                {
                    @unlink($goods_attachment_path);
                }
                return TRUE;
            }
        }
    }

    /**
     *   获取产品的留言
     * @param type $goods_id
     * @return type
     */
    public function get_goods_comments($goods_id)
    {
        $sql = "SELECT gc.* " .
                "FROM " . $this->table . " AS g " .
                "LEFT JOIN " . $this->db->get_table('shop_goods_comments') . " AS gc ON gc.goods_id=g.id " .
                "WHERE  gc.goods_id=" . $goods_id;
        $goods_comments_list = $this->db->get_results($sql, ARRAY_A);
        return $goods_comments_list;
    }

   

}